package com.shuimo.emoswxapi.wx.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.shuimo.emoswxapi.wx.common.enums.GlobalStatusEnum;
import com.shuimo.emoswxapi.wx.db.entity.TbUser;
import com.shuimo.emoswxapi.wx.db.service.ITbUserService;
import com.shuimo.emoswxapi.wx.exception.EmosException;
import com.shuimo.emoswxapi.wx.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Set;


@Service
@Scope("prototype")
@Slf4j
public class UserServiceImpl implements UserService {

    /**
     * 管理员邀请码
     */
    private static final String ROOT_REGISTER_CODE = "000000";

    /**
     * 管理员账号名
     */
    private static final String ROOT_NAME = "admin";

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Autowired
    private ITbUserService tbUserService;


    private String getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");
        if (openId == null || openId.length() == 0) {
            throw new EmosException(GlobalStatusEnum.TEMP_CODE_ERROR);
        }
        return openId;
    }

    /**
     * 注册
     *
     * @param registerCode
     * @param code
     * @param nickname
     * @param photo
     * @return
     */
    @Override
    public TbUser registerUser(String registerCode, String code, String nickname, String photo) {
        if (ROOT_REGISTER_CODE.equals(registerCode)) {
            boolean haveRootUser = tbUserService.haveRootUser();
            if (haveRootUser) {
                throw new EmosException(GlobalStatusEnum.ADMIN_EXIST);
            } else {
                //把当前用户绑定到ROOT帐户
                String openId = getOpenId(code);
                TbUser user = new TbUser();
                user.setCreateTime(LocalDateTime.now());
                user.setOpenId(openId);
                user.setNickname(nickname);
                user.setName(ROOT_NAME);
                user.setPhoto(photo);
                user.setRole("[0]");
                user.setStatus(1);
                user.setRoot(true);
                tbUserService.save(user);
                return user;
            }
        } else {
            return null;

        }
    }

    /**
     * 查询用户权限
     *
     * @param id
     * @return
     */
    @Override
    public Set<String> searchUserPermissions(Integer id) {
        return tbUserService.searchUserPermissions(id);
    }
}
